package com.simon.jkxj.ui.diet;

import android.content.Context;
import android.content.SharedPreferences;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

public class QuitSmokingDataManager {
    private static final String PREF_NAME = "quit_smoking_prefs";
    private static final String KEY_DATES = "checked_in_dates";
    private static final String KEY_START_DATE = "quit_start_date";
    private static Set<String> getCheckedDates(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        return new HashSet<>(prefs.getStringSet(KEY_DATES, new HashSet<>()));
    }
    private static void saveCheckedDates(Context context, Set<String> dates) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putStringSet(KEY_DATES, dates).apply();
    }
    public static void setQuitStartDate(Context context, String date) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putString(KEY_START_DATE, date).apply();
    }
    public static String getQuitStartDate(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        return prefs.getString(KEY_START_DATE, null);
    }
    public static void checkinToday(Context context) {
        Set<String> dates = getCheckedDates(context);
        String today = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        dates.add(today);
        saveCheckedDates(context, dates);
        if (getQuitStartDate(context) == null) {
            setQuitStartDate(context, today);
        }
    }
    public static boolean isTodayCheckedIn(Context context) {
        Set<String> dates = getCheckedDates(context);
        String today = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        return dates.contains(today);
    }
    public static int getTotalDays(Context context) {
        return getCheckedDates(context).size();
    }
    public static int getStreakDays(Context context) {
        Set<String> dates = getCheckedDates(context);
        if (dates.isEmpty()) return 0;
        int streak = 0;
        long oneDay = 24 * 60 * 60 * 1000L;
        long today = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        for (int i = 0; i < 365; i++) {
            String d = sdf.format(new Date(today - i * oneDay));
            if (dates.contains(d)) streak++;
            else break;
        }
        return streak;
    }
} 